﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taurus.Parking.DTO;
using Taurus.Platform.XML;
using System.Xml.Linq;
using Taurus.Platform.DTO;

namespace Taurus.Parking.XML
{
    class ParkingUserPersistence : BasePersistence<ParkingUser>
    {
        IPersistence<UserAccount> _per = new UserAccountPersistence();

        public override string FileName
        {
            get { return "ParkingUser.xml"; }
        }

        public override System.Xml.Linq.XElement GetEl(ParkingUser item)
        {
            var temp = from el in Root.Elements() where el.Attribute("UID").Value == item.UID select el;
            return temp.FirstOrDefault();
        }

        public override ParkingUser GetObject(string id)
        {
            ParkingUser pu = new ParkingUser();
            pu.UID = id;
            XElement el = GetEl(pu);
            return XChange(el);
        }

        protected override XElement XChange(ParkingUser item)
        {
            XElement puEl = new XElement("PU");
            puEl.SetAttributeValue("UID", item.UID);
           
            XElement priororty = new XElement("Priority");
            foreach (string t in item.PriorityUsers)
            {
                priororty.Add(new XElement("PriorityUser", t));
            }
            puEl.Add(priororty);
            
            XElement garage = new XElement("Garage",
                    new XElement("Scene", item.Garage.Scene),
                    new XElement("MoneyMinute", item.Garage.MoneyMinute)
                );
            puEl.Add(garage);
            
            return puEl;
        }

        protected override ParkingUser XChange(XElement item)
        {
            if (item!=null)
            {
                UserAccount ua = _per.GetObject(item.Attribute("UID").Value);
                ParkingUser pu = new ParkingUser(ua);
                var strList = from uid in item.Element("Priority").Elements("PriorityUser") select uid.Value;
                pu.PriorityUsers = strList.ToList();

                pu.Garage = new Garage();
                pu.Garage.MoneyMinute = item.Element("Garage").Element("MoneyMinute").Value;
                pu.Garage.Scene = item.Element("Garage").Element("Scene").Value;

                return pu;
            }
            return null;
        }
    }
}
